#pragma once


#include <iostream>
#include <string>
#include <vector>
#include <mutex>
#include <unordered_map>
#include <fstream>
#include "util.hpp"
#include "log.hpp"

namespace ns_index
{
    struct DocInfo
    {
        std::string title;   // 文档标题
        std::string content; // 文档内容
        std::string url;     // 文档的url
        uint64_t doc_id;     // 文档id
    };

    struct InvertedElem
    {
        std::string word; // 关键字
        uint64_t doc_id;       // 文档id
        int weight;       // 权重
    };
    // 倒排拉链
    typedef std::vector<InvertedElem> InvertedList;

    class Index
    {
    private:
        // 正排索引
        std::vector<DocInfo> forward_index;
        // 倒排索引----一个关键字对应多个InvertedElem
        std::unordered_map<std::string, InvertedList> inverted_index;

    private:
        Index() {}
        Index(const Index &) = delete;
        Index &operator=(const Index&) = delete;

        static Index *instance;
        static std::mutex mux;

    public:
        ~Index()
        {
        }

    public:
        // 单例模式
        static Index* GetInstance()
        {
            if (nullptr == instance)
            {
                mux.lock(); // 加锁
                if (nullptr == instance)
                {
                    instance = new Index();
                }
                mux.unlock(); // 解锁
            }
            return instance;
        }
        // 根据文档id找到文档内容
        DocInfo *GetForwardIndex(uint64_t doc_id)
        {
            if (doc_id >= forward_index.size())
            {
                std::cerr << "doc_id out of range" << std::endl;
                return nullptr;
            }
            return &forward_index[doc_id];
        }
        // 根据关键字找到倒排拉链
        InvertedList *GetInvertedList(const std::string &word)
        {
            auto iter = inverted_index.find(word);
            if (iter == inverted_index.end())
            {
                std::cerr << "not found" << std::endl;
                return nullptr;
            }
            return &(iter->second);
        }

        // 根据去标签，格式化的文档，建立正排和倒排索引
        // data/raw_html/raw.txt
        bool BuildIndex(const std::string &input)
        {
            // 以读的方式打开文件
            std::ifstream in(input, std::ios::in | std::ios::binary);
            if (!in.is_open())
            {
                std::cerr << "open" << input << "fail" << std::endl;
                return false;
            }

            std::string line;
            int count = 0;
            while (std::getline(in, line))
            {
                DocInfo* doc = BuildForwardIndex(line);
                
                if (doc == nullptr)
                {
                    std::cerr << "builtforwardindex fail" << std::endl;
                    continue;
                }

                BuiltInvertedIndex(*doc);
                count++;
                if(count % 50 == 0)
                {
                    // std::cout << "当前已经建立的索引文档：" << count << std::endl;
                    LOG(NORMAL, "当前已经建立的索引文档: " + std::to_string(count));
                }
            }

            return true;
        }

    private:
        // 构建正排索引
        DocInfo* BuildForwardIndex(const std::string &line)
        {
            // 1.解析line，字符串切分
            // line-> 3 string title content url
            std::vector<std::string> results;
            const std::string sep = "\3";
            ns_util::StringUtil::Split(line, &results, sep);
            if (results.size() != 3)
            {
                return nullptr;
            }
            // 2.字符串填充到DocInfo中
            DocInfo doc;
            doc.title = results[0];
            doc.content = results[1];
            doc.url = results[2];
            // 对应id就是doc在vector中的下标
            doc.doc_id = forward_index.size();
            // 3.插入到正排索引的vector中
            forward_index.push_back(std::move(doc));
            return &forward_index.back();
            // return &doc;
        }

        // 构建倒排索引
        bool BuiltInvertedIndex(const DocInfo &doc)
        {
            // doc -> title content url doc_id
            struct word_cnt
            {
                int title_cnt;
                int content_cnt;
                word_cnt()
                    : title_cnt(0), content_cnt(0)
                {}
            };
            // 词频存放表
            std::unordered_map<std::string, word_cnt> word_map;
            // 对标题进行分词
            std::vector<std::string> title_words;
            ns_util::JiebaUtil::CutString(doc.title, &title_words);
            // 对标题进行词频统计
            for (auto &s : title_words)
            {
                word_map[s].title_cnt++;
            }
            // 对文档内容进行分词
            std::vector<std::string> content_words;
            ns_util::JiebaUtil::CutString(doc.content, &content_words);
            // 对文档内容进行词频统计
            for (auto &s : content_words)
            {
                word_map[s].content_cnt++;
            }
#define X 10
#define Y 1
            // 自定义相关性
            for (auto &word_pair : word_map)
            {
                InvertedElem eml;
                eml.doc_id = doc.doc_id;
                eml.word = word_pair.first;
                eml.weight = X * word_pair.second.title_cnt + Y * word_pair.second.content_cnt;
                InvertedList &invertedlist = inverted_index[word_pair.first];
                invertedlist.push_back(std::move(eml));
            }
            return true;
        }
    };
    Index* Index::instance = nullptr;
    std::mutex Index::mux;

}